package com.atswust.shake.interceptor;

import com.atswust.shake.config.ResponBean;
import com.atswust.shake.utils.JWTutils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liushuai
 * @create 2022-02-06 11:52
 */

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中令牌
        String token = request.getHeader("token");
        ResponBean responBean = new ResponBean();
        try {
            //验证令牌
        JWTutils.verify(token);
            //放行请求
        return true;
        } catch (SignatureVerificationException e) {
            responBean.setMessage("无效签名");
        }catch (TokenExpiredException e){
            responBean.setMessage("token过期!");
        }catch (AlgorithmMismatchException e){
            responBean.setMessage("token算法不一致!");
        }catch (Exception e){
            responBean.setMessage("token无效!!");
        }
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(responBean);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
